package com.hcbd.tdwt.ui.htct.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.ui.htct.activity.SendMsgActivity_;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.GlobalParams;
import com.raizlabs.android.dbflow.sql.language.OperatorGroup;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.activity.AddContactActivity_;
import com.hcbd.tdwt.ui.xingyu.adapter.ContactMsgAdapter;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact_Table;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO_Table;
import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;

@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_chat_list_hlct)
public class MessageFragment extends BaseFragment {
    @ViewById(R.id.contact_rv)
    RecyclerView contactRv;
    @ViewById
    EditText searchEdit;
    @ViewById
    ImageView addContactImg;
    @ViewById
    TextView title;
    @ViewById
    RelativeLayout searchAreaRL;
    @ViewById
    LinearLayout searchLL;
    @ViewById
    RelativeLayout topRL,bgLL;
    @ViewById
    View titleView;
    private ContactMsgAdapter contactMsgAdapter;
    private List<BoxContact> contactList;
    private final int refresh_code = 5;
    @AfterViews
    protected void init() {
        contactList = SQLite.select().from(BoxContact.class).orderBy(BoxContact_Table.recentCommunicationTime, false).queryList();
        initContactData();
        initMsgRegister();
        title.setText("北斗短报文终端");
    }

    @Click
    void searchAreaRL() {
        searchEdit.requestFocus();
    }

    @Click
    void addContactImg() {
        Intent intent = new Intent();
        intent.setClass(getContext(), com.hcbd.tdwt.ui.fuda.common.activity.AddContactActivity_.class);
        startActivityForResult(intent, ADD_CONTACT_CODE);
    }

    @AfterTextChange
    void searchEdit() {
        String text = getTextStr(searchEdit);
        if ("".equals(text)) {
            contactList = SQLite.select().from(BoxContact.class).orderBy(BoxContact_Table.recentCommunicationTime, false).queryList();
        } else {
            OperatorGroup op = OperatorGroup.clause(OperatorGroup.clause().and(BoxContact_Table.boxId.like(TextUtils.concat("%", text, "%").toString()))).
                    or(OperatorGroup.clause().and(BoxContact_Table.name.like(TextUtils.concat("%", text, "%").toString())));
            contactList = SQLite.select().from(BoxContact.class).where(op).orderBy(BoxContact_Table.recentCommunicationTime, false).queryList();
        }
        initContactData();
    }

    @Click
    void sendMsgBtn() {
        Intent intent = new Intent();
        intent.setClass(getContext(), SendMsgActivity_.class);
        startActivityForResult(intent, refresh_code);
    }

    public void initContactData() {
        if (contactMsgAdapter == null) {
            contactMsgAdapter = new ContactMsgAdapter(this.getContext(), contactList);
            contactMsgAdapter.setHasStableIds(true);
        } else {
            contactMsgAdapter.notifyDataSetChanged(contactList);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
        contactRv.setLayoutManager(gridLayoutManager);
        contactRv.setAdapter(contactMsgAdapter);
        contactMsgAdapter.setOnItemClickListener(new ContactMsgAdapter.OnItemClickListener() {
            @Override
            public void onClick(BoxContact boxContact, View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), SendMsgActivity_.class);
                if (GlobalParams.rdCentreNumber.equals(boxContact.getBoxId())) {
                    intent.putExtra("receiverNumber", GlobalParams.rdCentreNumber);
                    intent.putExtra("entryMode", Constant.ENTRY_SEND_CENTER_NUMBER);
                } else {
                    intent.putExtra("receiverNumber", boxContact.getBoxId());
                    intent.putExtra("entryMode", Constant.ENTRY_SEND_USER_MSG);
                }

                intent.putExtra("receiverName", boxContact.getName());
                startActivityForResult(intent, refresh_code);
            }

            @Override
            public void onEdit(BoxContact boxContact) {
                Intent intent = new Intent();
                intent.setClass(getContext(), AddContactActivity_.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("boxContact", boxContact);
                intent.putExtras(bundle);
                intent.putExtra("entryMode", 1);
                startActivityForResult(intent, refresh_code);
            }

            @Override
            public void onDel(BoxContact boxContact) {
                try {
                    boxContact.delete();
                    SQLite.delete(UserMessageVO.class)
                            .where(UserMessageVO_Table.receiverNumber.eq(boxContact.getBoxId()))
                            .execute();
                    Constant.homePageIsRefresh = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                selectAll();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(UserMessageVO userMessage) {
        selectAll();
    }

    private final int ADD_CONTACT_CODE = 5;

    @OnActivityResult(refresh_code)
    public void resultMsgList(int resultCode) {
        if (resultCode == Activity.RESULT_OK) {
            selectAll();
        }
    }

    @Override
    public void onSwitch() {
        super.onSwitch();
        if (Constant.msgPageIsRefresh && contactMsgAdapter != null) {
            selectAll();
            Constant.msgPageIsRefresh = false;
        }
    }

    public void selectAll() {
        contactList = SQLite.select().from(BoxContact.class).orderBy(BoxContact_Table.recentCommunicationTime, false).queryList();
        initContactData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //不可见
            hideInputKeyBord();
        }
    }
}